/**
 * Created by bdbs on 2017/6/20.
 */
import React, { Component } from 'react';
import DropZone from 'react-dropzone';
import style from '../style.scss';
import readFile from '../util/readFile';
import parseSubtitle from '../util/parseSubtitle';
import TimerMixin from 'react-timer-mixin';
import SubTitle from './SubTitle';
import Media from './Media';
import fileHash from '../util/fileHash';

const encodeTypes = [
  'GBK',
  'utf8',
  'ucs2',
  'GB2312',
  'ascii',
  'binary',
  'base64',
  'hex',
];

class DropFile extends Component {
  // 构造
  constructor(props) {
    super(props);
    this.mixins = [TimerMixin];
    // 初始状态
    this.state = {
      images: [],
      video: null,
      // video: {
      //   path: '/Users/new/Downloads/mdjsj.MP4',
      // },
      // audio: null,
      // audio: {
      //   path: '/Users/new/Downloads/48.mp3',
      // },
      subtitle: [],
      time: 0,
      seek: 0,
      duration: 0,
    };
    this.encode = encodeTypes[0];
    this.offsetTime = 0;
    // this.getLocalSubtitle({
    //   lastModified: 1498182742000,
    //   lastModifiedDate: 'Fri Jun 23 2017 09:52:22 GMT+0800 (CST)',
    //   name:"48.lrc",
    //   path:"/Users/new/Downloads/48.lrc",
    //   preview:"blob:http://localhost:8003/dc51db42-cded-404f-bab9-8c8ff070771c",
    //   size:2878,
    //   type:"",
    //   webkitRelativePath:"",
    // });
  }

  readEncodeFile() {
    const fileType = this.subtitleFileData[2];
    readFile(this.subtitleFileData[0].path, this.encode).then((data) => {
      const subtitle = parseSubtitle(data, fileType)
      if (subtitle.length) {
        this.subtitleTimes = subtitle.map(centence => centence.time);
        this.setState({
          subtitle: subtitle,
        });
      }
    });
  }

  // 尝试通过统一字幕路径通过不同编码获取字幕内容
  readAllEncodeFile(filePath, fileType) {
    let index = 0;
    const len = encodeTypes.length;
    return new Promise((resolve, reject) => {
      const readEncodeFile = () => {
        const encodeType = encodeTypes[index++];
        readFile(filePath, encodeType).then((data) => {
          const subtitle = parseSubtitle(data, fileType)
          if (subtitle && subtitle.length) {
            this.subtitleTimes = subtitle.map(centence => centence.time);
            this.encode = encodeType;
            resolve(subtitle);
          } else {
            if (index < len) readEncodeFile();
          }
        }, reject);
      }
      readEncodeFile();
    })
  }
  
  getLocalSubtitle(filePath) {
    const subtitleReg = /.(lrc|srt)$/;
    const subtitleType = filePath.match(subtitleReg)[1];
    return new Promise((resolve, reject) => {
      this.readAllEncodeFile(filePath, subtitleType).then((srtSubtitle) => {
        resolve(srtSubtitle);
      }, reject);
    });
  }

  // 尝试通过拖拽进入的音频或者视频文件来获取本地字幕
  tryGetLocalSubtitle(filePath) {
    const lrcSubtitlePath = filePath.replace(/.\w+?$/, '.lrc');
    const srtSubtitlePath = filePath.replace(/.\w+?$/, '.srt');
    return new Promise((resolve, reject) => {
      this.readAllEncodeFile(lrcSubtitlePath, 'lrc').then((lrcSubtitle) => {
        resolve({
          subtitle: lrcSubtitle,
          path: lrcSubtitlePath,
        });
      }, (err) => {
        this.readAllEncodeFile(srtSubtitlePath, 'srt').then((srtSubtitle) => {
          resolve({
            subtitle: srtSubtitle,
            path: srtSubtitlePath,
          });
        }, reject);
      });
    })
  }

  componentWillUnMount() {
    clearInterval(this.timmer);
  }

  handleDrop (dropFiles, rejectFiles) {
    const images = dropFiles.filter(file => file.type.search(/^image/) === 0);
    const [video] = dropFiles.filter(file => file.type.search(/^video/) === 0);
    const [audio] = dropFiles.filter(file => file.type.search(/^audio/) === 0);
    window.zzeng = {};
    if (video || audio) {
      this.tryGetLocalSubtitle(dropFiles[0].path).then(({ subtitle, path }) => {
        console.log('dropFiles[0]', dropFiles[0]);
        fileHash(path).then((hash) => {
          window.zzeng.subtitleHash = hash;
          window.zzeng.subtitle = subtitle;
          window.zzeng.fileName = dropFiles[0].name;
        });

        this.props.onDrop({
          subtitle,
          media: video || audio,
        });
      }, () => {
        this.props.onDrop({
          media: video || audio,
        });
      })
    }

    fileHash(dropFiles[0].path).then((hash) => {
      if (!window.zzeng) window.zzeng = {};
      window.zzeng.fileHash = hash;
    });

    const subtitleReg = /.(lrc|srt)$/;
    const isSubtitle = dropFiles[0].name.match(subtitleReg);
    if (isSubtitle) {
      this.getLocalSubtitle(dropFiles[0].path).then((subtitle) => {
        this.props.onDrop({
          subtitle,
        });
      });
    }
  }

  handleEncodeChange() {
    this.encode = this.refs.encodeSelect.value;
    this.readEncodeFile();
  }

  handleSeek(seekTo) {
    this.setState({
      seek: seekTo,
    });
  }

  render() {
    return (
      <DropZone className={style.dropzone} disableClick onDrop={this.handleDrop.bind(this)}>
        { this.props.children }
      </DropZone>
    );
  }
}

export default DropFile;
